import docx
import fitz  # PyMuPDF
import os

class ResumeParser:
    """
    A class to parse resumes from various file formats (PDF, DOCX, TXT).
    """
    def __init__(self, supported_formats=None):
        if supported_formats is None:
            self.supported_formats = ['.pdf', '.docx', '.txt']
        else:
            self.supported_formats = supported_formats

    def _extract_text_from_pdf(self, file_path):
        """Extracts text from a PDF file using PyMuPDF."""
        try:
            with fitz.open(file_path) as doc:
                text = "".join(page.get_text() for page in doc)
            if not text.strip():
                # Fallback for image-based PDFs, requires OCR which is out of scope for now.
                # As suggested in the tutorial.
                print(f"Warning: PDF file '{file_path}' might be image-based. Extracted text is empty.")
            return text
        except Exception as e:
            print(f"Error parsing PDF file '{file_path}': {e}")
            return ""

    def _extract_text_from_docx(self, file_path):
        """Extracts text from a DOCX file."""
        try:
            doc = docx.Document(file_path)
            return "\n".join([paragraph.text for paragraph in doc.paragraphs])
        except Exception as e:
            print(f"Error parsing DOCX file '{file_path}': {e}")
            return ""

    def _extract_text_from_txt(self, file_path):
        """Extracts text from a TXT file."""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()
        except UnicodeDecodeError:
            # Fallback to GBK as suggested in the tutorial
            try:
                with open(file_path, 'r', encoding='gbk') as file:
                    return file.read()
            except Exception as e:
                print(f"Error parsing TXT file '{file_path}' with both UTF-8 and GBK: {e}")
                return ""
        except Exception as e:
            print(f"Error parsing TXT file '{file_path}': {e}")
            return ""

    def parse_resume(self, file_path):
        """
        Parses a resume file and returns its text content.
        
        Args:
            file_path (str): The absolute path to the resume file.

        Returns:
            str: The extracted text from the resume, or an empty string if parsing fails.
        """
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"The file was not found at path: {file_path}")

        file_extension = os.path.splitext(file_path)[1].lower()

        if file_extension not in self.supported_formats:
            raise ValueError(f"Unsupported file format: '{file_extension}'. Supported formats are: {self.supported_formats}")

        if file_extension == '.pdf':
            return self._extract_text_from_pdf(file_path)
        elif file_extension == '.docx':
            return self._extract_text_from_docx(file_path)
        elif file_extension == '.txt':
            return self._extract_text_from_txt(file_path)
        
        return ""